<template>
  <div class="catalog-path">
    <el-breadcrumb ref="catalogPath" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item v-for="(item, index) in path"
        class="catalog-path__item"
        :key="item.id"
        :data-index="index"
        :data-id="item.id">
        {{ item.name }}
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>
</template>

<script>

import $ from 'jquery'

export default {
  name: 'WsCatalogPath',
  components: {
  },
  props: {
    path: {
      type: Array,
      default () {
        return []
      }
    }
  },
  data () {
    return {
    }
  },
  updated () {
    // 每次更新需要重新绑定事件，有可能增加了项目
    let children = this.$refs.catalogPath.$children
    for (let i = 0; i < children.length - 1; i++) {
      const child = children[i]
      let link = child.$refs.link
      link.removeEventListener('click', this.handleItemClick)
      link.addEventListener('click', this.handleItemClick)
    }
  },
  methods: {

    /**
     * 点击导航项
     * @private
     */
    handleItemClick (e) {
      let id = $(e.target).parent().attr('data-id')
      let item = this.findItemById(id)
      if (item) {
        this.$emit('goback', item, this)
      }
    },

    /**
     * 查找指定id的数据
     * @private
     * @param {String} id 数据id
     */
    findItemById (id) {
      for (let i = 0; i < this.path.length; i++) {
        const item = this.path[i]
        if (item.id === id) {
          return item
        }
      }
      return null
    }
  }
}
</script>
